package com.joeljhou.project.core.listener;

import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.write.handler.CellWriteHandler;
import com.alibaba.excel.write.handler.context.CellWriteHandlerContext;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import com.alibaba.excel.write.metadata.style.WriteFont;
import com.joeljhou.project.form.Component;
import org.apache.poi.ss.usermodel.IndexedColors;

import javax.swing.*;
import java.util.Arrays;
import java.util.stream.Collectors;

public class ExcelWriteStyleListener implements CellWriteHandler {

    private String[] tail = new String[]{
            "最   大   值：",
            "最   小   值：",
            "平   均   值：",
            "良   品   数：",
            "非 良 品 数："
    };

    @Override
    public void afterCellDataConverted(CellWriteHandlerContext context) {
        // 判断是头的情况
        if (context.getRowIndex() < 4) {
            return;
        }

        //判断是尾的情况
        if (Arrays.stream(tail).collect(Collectors.toList())
                .contains(context.getRow().getCell(0).getStringCellValue())) {
            return;
        }

        //判断时间列的情况
        if (context.getCell().getColumnIndex() % 2 == 0) {
            return;
        }

        //判断沒有数据的情况
        WriteCellData<?> cellData = context.getFirstCellData();
        String cellStrData = cellData.getStringValue();
        if (cellStrData == null) {
            return;
        }
        Component component = Component.getInstance();
        JTextField pullTextField = component.getPullTextField();
        String pullText = pullTextField.getText();
        double pullValue = Double.parseDouble(pullText);  //拉力值
        double parseDouble = Double.parseDouble(cellData.getStringValue());

        //正常数据不渲染
        if (parseDouble >= pullValue) {
            return;
        }

        // 设置单个单元格的样式（字体显示红色）
        WriteCellStyle writeCellStyle = cellData.getOrCreateStyle();
        WriteFont writeFont = new WriteFont();
        writeFont.setColor(IndexedColors.RED.getIndex());
        writeCellStyle.setWriteFont(writeFont);
    }


}
